package com.chanzany.singleton.type5;


public class SingletonTest {
    public static void main(String[] args) throws InterruptedException {
//        Singleton instance = Singleton.getInstance();
//        Singleton instance2 = Singleton.getInstance();
        for (int i = 0; i < 1000; i++) {
            new Thread(()->{
                Singleton instance = Singleton.getInstance();
            }).start();
        }
    }
}

/**
 * 懒汉式（提升了效率但是线程不安全）
 */
class Singleton{
    private Singleton(){}
    private static Singleton instance;
    public  static Singleton getInstance(){
        if (instance==null) {
            //减少锁的粒度
            synchronized (Singleton.class){
                System.out.println("创建");
                instance = new Singleton();
            }
        }
        return instance;
    }
}
